define(["knockout", 'jquery', 'dynaWindow', 'text!./account-editor.btl', 'jqx-all', 'ko-rest', 'ko-mapping'], 
		function (ko, $, dynaWindow, curBtl) {  		
    function AccountEditor(params) {	
    	var self = this;
    	
    	self.service = ko.rest.service('/rest/auth/account');
    	
    	self.vm = ko.mapping.fromJS({id:-1, email:'', name:'', password:'', salt:''});
    	self.vm.divId = params.id;
    	self.vm.initContent = function () {
    		var element = $(this.element);
    		element.jqxWindow({ okButton: element.find('#btn_OK')});
    		element.jqxWindow({ cancelButton: element.find('#btn_Cancel')}); 
    		
    		element.find("#btn_OK").click(function () {
    			if (self.isEditor) {
    				self.update();
    			} else {
    				self.create();
    			}
    			
            });
    		
    		element.on('open', function (event) { 
            }); 
            
    		element.on('close', function (event) { 
            	if (event.args.dialogResult.OK) {
            		
            	}
            });
        }
    	
    	self.id = null;
    	self.isEditor = false;
    	ko.postbox.subscribe(function(data) {
    		self.id = data.id;
    		self.isEditor = data.isEditor;
    		if (self.isEditor) {
            	self.service.load(self.id, function(data) {
            		self.vm.id(data.id);
            		self.vm.email(data.email);
            		self.vm.name(data.name);
            		self.vm.password(data.password);
            		self.vm.salt(data.salt);
            	});
    		} else {
        		self.vm.id(null);
        		self.vm.email('');
        		self.vm.name('');
        		self.vm.password('');
        		self.vm.salt('');
    		}

    	}, null, "account-editor-sub");
	}  
    
    AccountEditor.prototype.create = function() {
    	var self =  this;
    	var data = ko.mapping.toJS(self.vm);
    	self.service.save(data, function() {
    		ko.postbox.notifySubscribers("close", "account-editor-pub");
    	});
    }
    
    AccountEditor.prototype.update = function() {
    	var self =  this;
    	var data = ko.mapping.toJS(self.vm);
    	self.service.update(data, function() {
    		ko.postbox.notifySubscribers("close", "account-editor-pub");
    	});
    }
    
    return { 
    	viewModel: {
	        createViewModel: function (params, componentInfo) {
	            var editor = new AccountEditor({ id: params.id});
	            return editor.vm;
	        }
    	}, 
    	template: curBtl
    };
});
